module Digit2word
  class Dict
    attr_reader :argv
    DEFAULT_DICT_PATH = Digit2word.root.join('config', 'dict')

    def initialize(argv = ARGV)
      @argv = argv
    end

    def show
      puts 'Current dictionary:'
      puts File.open(self.class.dict_config_path, 'r').read
    rescue
      puts "Warnning: Dictionary '#{self.class.dict_config_path}' not found!"
    end

    def set_path(new_path)
      new_path = new_path.to_s.empty? ? '' : Digit2word.root.join(new_path).to_s
      current_app_config = File.open(APP_CONFIG){ |file| YAML.load(file) }
      current_app_config[:dict_path] = new_path
      File.open(APP_CONFIG, "w") {|f| f.write current_app_config.to_yaml }
      # puts "New dictionary located: #{new_path}"
    end

    def run!
      if @argv.empty?
        show
      else
        set_path(@argv.last)
      end
    end

    def self.words
      File.new(dict_config_path).map(&:strip)
    end

    def self.word_pattern
      @word_pattern ||= Regexp.new(words.map{|x| Regexp.escape(x) }.join('|'), true)
    end

    def self.dict_config_path
      custom_dict_config_path = File.open(APP_CONFIG){ |file| YAML.load(file) }[:dict_path]
      custom_dict_config_path.empty? ? DEFAULT_DICT_PATH : custom_dict_config_path
    end
  end
end
